package com.insider.dao.JDBC;


import com.insider.dao.UserDao;
import com.insider.domain.User;
import com.insider.domain.row.UserRowMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.SQLException;

@Component
public class UserDaoImpl extends JdbcDaoSupport implements UserDao {

    @Autowired
    DataSource dataSource;

    private static final String USER_SAVE_SQL = "INSERT INTO user (user_id, login, password) VALUES (?, ?, ?)";
    private static final String USER_DELETE_SQL = "DELETE FROM user WHERE user_id=?";
    private static final String USER_SEARCH_SQL = "SELECT * FROM user WHERE user_id = ?";
    private static final String USER_UPDATE_SQL = "UPDATE user SET user_id=?, login=?, password=?";

    @PostConstruct
    protected void initDao() {
        if (getDataSource() == null) {
            setDataSource(dataSource);
        }
    }


    @Override
    public void save(User user) throws SQLException {
        getJdbcTemplate().update(USER_SAVE_SQL,
                user.getId(),
                user.getLogin(),
                user.getPassword());

    }

    @SuppressWarnings("unchecked")
    @Override
    public User find(Integer userId) throws SQLException {

        return (User) getJdbcTemplate().queryForObject(USER_SEARCH_SQL,
                new Object[]{userId},
                new UserRowMapper());
    }

    @Override
    public void update(User user) throws SQLException {
        getJdbcTemplate().update(USER_UPDATE_SQL,
                user.getId(),
                user.getLogin(),
                user.getPassword());
    }

    @Override
    public void delete(User user) throws SQLException {
        getJdbcTemplate().update(USER_DELETE_SQL,
                user.getId());
    }

}
